<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';
import { defineAsyncComponent, shallowRef, watchEffect } from 'vue';
import { Card, Input, Switch } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { getThemesWidgetSetting } from '#/api/admin/theme';
import { useThemeStore } from '#/store';
import { formatValues, generateFormSchema } from '#/utils';

const iframeUrl =ref();


const tabList = [
  {
    key: 'attribute',
    tab: '属性',
  },
  {
    key: 'css',
    tab: '样式',
  },
];
const isInput = ref(false);
const key = ref('attribute');
const noTitleKey = ref('attribute');
const state: any = reactive({
  file_id: '',
  theme: '',
  block_name: '',
  widget_id: '',
  widget: {},
});

/** 提交 */
const onSubmit = async () => {
  const widget = {
    title: state.widget.title,
    display: state.widget.display,
    vars: state.widget.vars,
    css: state.widget.css,
  };
  useThemeStore().onPostThemesWidgetSetting(widget);
};

/** 文件设置表单 */
const [AttributeForm, AttributeFormApi] = useVbenForm({
  layout: 'vertical',
  showDefaultActions: false,
  // 提交函数
  handleSubmit: (values) => {
    const formApiState = AttributeFormApi.getState();
    const formApiStateSchema = formApiState?.schema || [];
    const newValues = formatValues(formApiStateSchema, values);
    state.widget.vars = newValues;
  },
});

/** 文件设置表单 */
const [CssForm, CssFormApi] = useVbenForm({
  layout: 'vertical',
  showDefaultActions: false,
  // 提交函数
  handleSubmit: (values) => {
    state.widget.css = values;
  },
});

const onSetCssFormData = async (config: any) => {
  const { schema, values } = generateFormSchema(config);
  CssFormApi.setState({ schema });
  CssFormApi.setValues(values);
};

const onSetAttributeForm = async (config: any) => {

  const { schema, values } = generateFormSchema(config);

  AttributeFormApi.setState({ schema });
  AttributeFormApi.setValues(values);
};
const [Modal, ModalApi] = useVbenModal({
  fullscreenButton: true,
  draggable:true,
  async onConfirm() {
    await AttributeFormApi.validateAndSubmitForm();
    await CssFormApi.validateAndSubmitForm();
    await onSubmit();

    ModalApi.close();
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      key.value = 'attribute';
      const modalData: any = await ModalApi.getData();
      state.block_name = modalData.blockName;
      state.file_id = modalData.file_id;
      try {
        const {
          data: { widget },
        } = await getThemesWidgetSetting({
          block_name: modalData.blockName,
          file_id: modalData.file_id,
          widget_id: modalData.widget.id,
        });
        state.widget_id = modalData.widget.id;
        state.widget = widget;
        state.widget.display = Number(state.widget.display);
       
        onSetAttributeForm(widget.vars);
        onSetCssFormData(widget.css);
      } catch (error) {
        console.error('获取配置失败:', error);
        throw error; // 如果发生错误，向上抛出以便调用者处理
      }
    }
  },
});

const onTabChange = async (value: string, type: string) => {
  if (type === 'key') {
    key.value = value;
  } else if (type === 'noTitleKey') {
    noTitleKey.value = value;
  }
};



// 2. 监听条件变化
watchEffect(() => {
  console.log(state)
  if (state.widget?.type === 'vue' && state.widget.type_url) {

    iframeUrl.value =state.widget.type_url
  }
});


</script>
<template>
  <Modal class="w-[1500px]">
    <Card>
      <template #title>
        <span v-if="!isInput" @click="isInput = !isInput">{{
          state.widget.title
        }}</span>
        <Input
          v-else
          v-model:value="state.widget.title"
          placeholder="请输入控件标题"
          style="width: 200px"
          @press-enter="isInput = !isInput"
        />
      </template>
      <template #extra>
        <Switch
          v-model:checked="state.widget.display"
          :checked-value="1"
          :un-checked-value="0"
          checked-children="显示"
          un-checked-children="隐藏"
        />
      </template>
      <Card
        :active-tab-key="noTitleKey"
        :tab-list="tabList"
        style="width: 100%"
        @tab-change="(key) => onTabChange(key, 'noTitleKey')"
      >
       <iframe
      :src="iframeUrl"
      frameborder="0"
      :style="{ display: noTitleKey === 'attribute' ? 'block' : 'none',width:'100%' }"
    ></iframe>
        <AttributeForm
          :style="{ display: noTitleKey === 'attribute' ? 'block' : 'none' }"
        >
      </AttributeForm>

        <CssForm
          :style="{ display: noTitleKey === 'css' ? 'block' : 'none' }"
        />
      </Card>
    </Card>
  </Modal>
</template>
